<template>
  <section class="todoapp">
     <HmHeader @add-event="handleAdd"></HmHeader>
     <HmMain :list="showList" @change-status-event="changeStatus" @delete-event="listDelete" @change-all-event="handleAll"></HmMain>
     <HmFooter :list="list" @clearall-event="clearALL" :status="status" @status-event="status = $event"></HmFooter>
  </section>
</template>
 
<script>
const obj = {
  "#/": "all",
  "#/completed": "done",
  "#/active": "undone",
}
import HmHeader from "./components/hm-header.vue"
import HmFooter from "./components/hm-footer.vue"
import HmMain from "./components/hm-main.vue"
export default {
  components: {
    HmHeader,
    HmMain,
    HmFooter,
  },
  props: {},
  data() {
    return {
      list: JSON.parse(localStorage.getItem('list')) || [
        {id: 1, title: '睡觉', done: false},
        {id: 1, title: '吃饭', done: false},
        {id: 1, title: '玩游戏', done: false}
      ],
      status: obj[location.hash] || 'all'
    };
  },
  computed: {
    showList() {
      if (this.status === "all") {
        return this.list;
      } else if (this.status === "done") {
        return this.list.filter((item) => item.done === true);
      } else {
        return this.list.filter((item) => item.done === false);
      }
    },
  },
  created() {},
  methods: {
    listDelete(id){
      const index = this.list.findIndex(item => item.id === id);
      this.list.splice(index, 1);
    },
    changeStatus(id){
      const obj = this.list.find((item) => item.id === id);
      obj.done = !obj.done;
    },
    handleAdd(title){
      const id = this.list.length === 0? 1 : this.list.slice(-1)[0].id + 1;
      const obj = {
        id,
        title,
        done: false,
      }
      this.list.push(obj)
    },
    handleAll(value){
      this.list = this.list.map(item => {
        item.done = value
        return item
      })
    },
    clearALL(){
      this.list = this.list.filter(item => item.done === false)
    }
  },
  watch: {
    list: {
      handler(newValue){
        window.localStorage.setItem("list", JSON.stringify(newValue));
      },
      deep: true,
    },
  },
};
</script>

<style scoped>
     
</style>